import React, { useState, useEffect } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import "./DailyGoal.css"; // 引入样式

const DailyGoal = () => {
    const [dailyGoals, setDailyGoals] = useState([]); // 当前每日目标列表
    const [newGoalDescription, setNewGoalDescription] = useState(""); // 新目标描述
    const [newGoalMinutes, setNewGoalMinutes] = useState(""); // 新目标总时间
    const [editingGoalId, setEditingGoalId] = useState(null); // 当前编辑的目标ID
    const [editingDescription, setEditingDescription] = useState(""); // 编辑目标描述
    const [editingMinutes, setEditingMinutes] = useState(""); // 编辑目标总时间

    const navigate = useNavigate();
    const userId = 1; // 假设当前用户的 `user_id` 是 1，实际应用中可以从登录信息中获取

    // 获取所有每日目标
    useEffect(() => {
        const fetchDailyGoals = async () => {
            try {
                const response = await axios.get(`/api/daily-goals/${userId}`); // 根据 user_id 获取目标
                if (response.status === 200 && Array.isArray(response.data)) {
                    setDailyGoals(response.data);
                }
            } catch (error) {
                console.error("获取每日目标失败：", error);
                toast.error("获取每日目标失败，请稍后再试。");
            }
        };

        fetchDailyGoals();
    }, [userId]); // 仅在组件加载时执行

    // 添加新每日目标
    const addDailyGoal = async () => {
        if (newGoalDescription.trim() === "" || newGoalMinutes.trim() === "") {
            toast.warning("请填写完整的每日目标内容！");
            return;
        }

        const newGoal = {
            userId, // 添加 user_id 到新目标数据中
            description: newGoalDescription,
            completedMinutes: 0, // 初始为0
            totalMinutes: parseInt(newGoalMinutes, 10),
        };

        try {
            const response = await axios.post("/api/daily-goals", newGoal); // 调用后端保存目标的接口
            if (response.status === 201) {
                setDailyGoals([...dailyGoals, response.data]); // 添加新目标到列表
                setNewGoalDescription("");
                setNewGoalMinutes("");
                toast.success("每日目标已添加！");
            }
        } catch (error) {
            console.error("保存每日目标时发生错误：", error);
            if (error.response && error.response.status === 400) {
                toast.error("每日目标格式不正确，请检查后再试。");
            } else {
                toast.error("保存每日目标失败，请稍后再试！");
            }
        }
    };

    // 启动编辑模式
// 取消编辑
// 更新每日目标
// 删除每日目标
    const deleteDailyGoal = async (goalId) => {
        if (!window.confirm("确定要删除这个每日目标吗？")) return;

        try {
            const response = await axios.delete(`/api/daily-goals/${goalId}`);
            if (response.status === 200) {
                setDailyGoals(dailyGoals.filter((goal) => goal.id !== goalId));
                toast.success("每日目标已删除！");
            }
        } catch (error) {
            console.error("删除每日目标时发生错误：", error);
            if (error.response && error.response.status === 404) {
                toast.error("目标未找到，请刷新页面。");
            } else {
                toast.error("删除每日目标失败，请稍后再试！");
            }
        }
    };

    return (
        <div className="daily-goal-container">
            <div className="update-goal-section">
                <h4>设置新每日目标</h4>
                <input
                    type="text"
                    placeholder="目标描述 (例如: 练习词汇)"
                    value={newGoalDescription}
                    onChange={(e) => setNewGoalDescription(e.target.value)}
                    className="goal-input"
                />
                <input
                    type="number"
                    placeholder="总分钟数"
                    value={newGoalMinutes}
                    onChange={(e) => setNewGoalMinutes(e.target.value)}
                    className="goal-input"
                    min="1"
                />
                <button onClick={addDailyGoal} className="update-goal-button">
                    添加目标
                </button>
            </div>

            {dailyGoals.length > 0 ? (
                <div className="goal-list-section">
                    <h4>当前每日目标列表</h4>
                    {dailyGoals.map((goal) => (
                        <div key={goal.id} className="goal-item">
                            <div className="goal-details">
                                <p><strong>目标描述：</strong>{goal.description}</p>
                                <p><strong>已完成时间：</strong>{goal.completedMinutes} 分钟 / {goal.totalMinutes} 分钟</p>
                                <div className="goal-actions">
                                    <button onClick={() => deleteDailyGoal(goal.id)} className="delete-goal-button">
                                        删除
                                    </button>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>
            ) : (
                <p>还没有设置每日目标。</p>
            )}
        </div>
    );
};

export default DailyGoal;